package petshop.gui;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.text.JTextComponent;
import petshop.classes.Animal;
import petshop.classes.DocumentoMascara;

/**
 *
 * @author arthur
 */
public class JanelaAnimal extends Janela {

    TipoJanela tipo;
    JanelaCliente janelaCliente;
    Animal animal;
    int index;

    /** Creates new form JanelaAnimal */
    public JanelaAnimal(JanelaCliente janelaCliente, TipoJanela tipo, Animal a) {
        this.tipo = tipo;
        initComponents();

        if(a == null) {
            animal = new Animal();
        } else {
            animal = a;
        }

        this.janelaCliente = janelaCliente;

        this.setLocationRelativeTo(this.getContentPane());

        campoNome.setDocument(new DocumentoMascara(50));
        campoRaca.setDocument(new DocumentoMascara(50));
        areaInformacoes.setDocument(new DocumentoMascara(400));

        if(tipo == TipoJanela.INFORMACAO){
            desabilitarCampos();
            preencher();
        } else if(tipo == TipoJanela.ALTERACAO){
            this.botaoAdicionar.setText("Alterar");
            preencher();
        }

        reiniciar();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        campoNome = new javax.swing.JTextField();
        campoRaca = new javax.swing.JTextField();
        comboEspecie = new javax.swing.JComboBox();
        botaoCancelar = new javax.swing.JButton();
        botaoAdicionar = new javax.swing.JButton();
        comboSexo = new javax.swing.JComboBox();
        scrollInformacoes = new javax.swing.JScrollPane();
        areaInformacoes = new javax.swing.JTextArea();
        campoDataNascimento = new javax.swing.JFormattedTextField();
        labelNome = new javax.swing.JLabel();
        labelDataNascimento = new javax.swing.JLabel();
        labelEspecie = new javax.swing.JLabel();
        labelInformacoes = new javax.swing.JLabel();
        labelSexo = new javax.swing.JLabel();
        labelRaca = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Animal");
        setResizable(false);
        getContentPane().setLayout(new java.awt.GridBagLayout());
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 115;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
        getContentPane().add(campoNome, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 80;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
        getContentPane().add(campoRaca, gridBagConstraints);

        comboEspecie.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "CÃO", "GATO", "AVE", "ROEDOR", "OUTRO" }));
        comboEspecie.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                mudarComboEspecie(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 40;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
        getContentPane().add(comboEspecie, gridBagConstraints);

        botaoCancelar.setText("Cancelar");
        botaoCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cancelar(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 6;
        gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
        gridBagConstraints.ipadx = 30;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(botaoCancelar, gridBagConstraints);

        botaoAdicionar.setText("Adicionar");
        botaoAdicionar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cadastrar(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 6;
        gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
        gridBagConstraints.ipadx = 30;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(botaoAdicionar, gridBagConstraints);

        comboSexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "MACHO", "FÊMEA" }));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 35;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
        getContentPane().add(comboSexo, gridBagConstraints);

        areaInformacoes.setColumns(20);
        areaInformacoes.setLineWrap(true);
        areaInformacoes.setRows(5);
        scrollInformacoes.setViewportView(areaInformacoes);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.gridwidth = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 150;
        gridBagConstraints.ipady = 20;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
        getContentPane().add(scrollInformacoes, gridBagConstraints);

        try {
            campoDataNascimento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        campoDataNascimento.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        campoDataNascimento.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                ganharFoco(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
        getContentPane().add(campoDataNascimento, gridBagConstraints);

        labelNome.setFont(new java.awt.Font("Ubuntu", 1, 12));
        labelNome.setText("Nome");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        getContentPane().add(labelNome, gridBagConstraints);

        labelDataNascimento.setFont(new java.awt.Font("Ubuntu", 1, 12)); // NOI18N
        labelDataNascimento.setText("Data de Nasc.");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        getContentPane().add(labelDataNascimento, gridBagConstraints);

        labelEspecie.setFont(new java.awt.Font("Ubuntu", 1, 12));
        labelEspecie.setText("Espécie");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        getContentPane().add(labelEspecie, gridBagConstraints);

        labelInformacoes.setText("Informações Adicionais");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        getContentPane().add(labelInformacoes, gridBagConstraints);

        labelSexo.setFont(new java.awt.Font("Ubuntu", 1, 12));
        labelSexo.setText("Sexo");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        getContentPane().add(labelSexo, gridBagConstraints);

        labelRaca.setFont(new java.awt.Font("Ubuntu", 0, 12)); // NOI18N
        labelRaca.setText("Raça");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        getContentPane().add(labelRaca, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelar(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelar
        cancelar();
}//GEN-LAST:event_cancelar

    private void cadastrar(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cadastrar
        if(!existemDependencias()){
            if(tipo == TipoJanela.CADASTRO) {
                cadastrar();
            } else if(tipo == TipoJanela.ALTERACAO) {
                alterar();
            }

            this.dispose();
        }
    }//GEN-LAST:event_cadastrar

    private void mudarComboEspecie(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_mudarComboEspecie
        if(comboEspecie.getSelectedIndex() == 4){
            labelRaca.setText(("Qual?"));
            labelRaca.setFont(new java.awt.Font("Ubuntu", 1, 12));
        } else {
            labelRaca.setText(("Raça"));
            labelRaca.setFont(new java.awt.Font("Ubuntu", 0, 12));
        }
    }//GEN-LAST:event_mudarComboEspecie

    private void ganharFoco(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ganharFoco
        JTextComponent t = (JTextComponent) evt.getComponent();
        int posicao = 0;

        for(int i = 0; i < t.getText().length(); i++){
            if(!t.getText().substring(posicao, posicao + 1).equals(" ")) {
                posicao++;
            } else {
                break;
            }
        }

        t.setCaretPosition(posicao);
    }//GEN-LAST:event_ganharFoco

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new JanelaAnimal(null, TipoJanela.CADASTRO, null).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea areaInformacoes;
    private javax.swing.JButton botaoAdicionar;
    private javax.swing.JButton botaoCancelar;
    private javax.swing.JFormattedTextField campoDataNascimento;
    private javax.swing.JTextField campoNome;
    private javax.swing.JTextField campoRaca;
    private javax.swing.JComboBox comboEspecie;
    private javax.swing.JComboBox comboSexo;
    private javax.swing.JLabel labelDataNascimento;
    private javax.swing.JLabel labelEspecie;
    private javax.swing.JLabel labelInformacoes;
    private javax.swing.JLabel labelNome;
    private javax.swing.JLabel labelRaca;
    private javax.swing.JLabel labelSexo;
    private javax.swing.JScrollPane scrollInformacoes;
    // End of variables declaration//GEN-END:variables

    protected final void reiniciar() {

        campoNome.setText("");
        comboSexo.setSelectedIndex(-1);
        comboEspecie.setSelectedIndex(-1);
        campoDataNascimento.setText("");
        campoRaca.setText("");
        areaInformacoes.setText("");
    }

    protected final boolean existemDependencias() {
        String msg = "Você esqueceu de preencher os \nseguintes campos obrigatórios:\n\n";

        boolean existeDependencias = false;

        if(!campoDataNascimento.getText().substring(0, 1).equals(" ")){
            if(!dataValida(campoDataNascimento.getText())){
                JOptionPane.showMessageDialog(this.getContentPane(), "A data é inválida");
                return true;
            }
        } else {
            msg += "- DATA\n";
            existeDependencias = true;
        }

        if(campoNome.getText().equals("")){
            msg += "- NOME\n";
            existeDependencias = true;
        }
        if(comboSexo.getSelectedIndex() == 0){
            msg += "- SEXO\n";
            existeDependencias = true;
        }
        if(comboEspecie.getSelectedIndex() == 0){
            msg += "- ESPÉCIE\n";
            existeDependencias = true;
        }
        if(labelRaca.getText().equals("Qual?")){
            if(campoRaca.getText().equals("")){
                msg += "- ESPÉCIE ESPECÍFICA\n";
            }
            existeDependencias = true;
        }

        if(existeDependencias){
            JOptionPane.showMessageDialog(this.getContentPane(), msg);
        }

        return existeDependencias;
    }

    public boolean dataValida(String dateStr) {
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        Calendar cal = new GregorianCalendar();
        try {
            // gerando o calendar
            cal.setTime(df.parse(dateStr));
        } catch(ParseException ex){
            Logger.getLogger(JanelaAnimal.class.getName()).log(Level.SEVERE, null, ex);
        }

        // separando os dados da string para comparacao e validacao
        String[] data = dateStr.split("/");
        String dia = data[0];
        String mes = data[1];
        String ano = data[2];

        // testando se hah discrepancia entre a data que foi
        // inserida no caledar e a data que foi passada como
        // string. se houver diferenca, a data passada era
        // invalida
        if((new Integer(dia)).intValue() != (new Integer(cal.get(Calendar.DAY_OF_MONTH))).intValue()){
            // dia nao casou
            return (false);
        } else if((new Integer(mes)).intValue() != (new Integer(cal.get(Calendar.MONTH) + 1)).intValue()){
            // mes nao casou
            return (false);
        } else if((new Integer(ano)).intValue() != (new Integer(cal.get(Calendar.YEAR))).intValue()){
            // ano nao casou
            return (false);
        }

        return (true);
    }

    protected final void preencher() {
        SimpleDateFormat data = new SimpleDateFormat("dd/MM/yyyy");

        campoNome.setText(animal.getNome());
        if(animal.getSexo() == 'M'){
            comboSexo.setSelectedIndex(0);
        } else {
            comboSexo.setSelectedIndex(1);
        }
        campoDataNascimento.setText(data.format(animal.getDataNasc().getTime()));
        comboEspecie.setSelectedItem(animal.getEspecie());
        campoRaca.setText(animal.getRaca());
        areaInformacoes.setText(animal.getInfo());
    }

    private Animal gerarAnimal() {
        String[] d = campoDataNascimento.getText().split("/");

        String nome = campoNome.getText();
        char sexo;
        if(comboSexo.getSelectedIndex() == 1){
            sexo = 'M';
        } else {
            sexo = 'F';
        }
        GregorianCalendar cal = new GregorianCalendar(Integer.valueOf(d[2]),
                Integer.valueOf(d[1]), Integer.valueOf(d[0]));
        String especie = (String) comboEspecie.getSelectedItem();
        String raca = "";
        String info = "";

        raca = campoRaca.getText();
        info = areaInformacoes.getText();

        Animal a = new Animal(nome, sexo, cal, especie, raca, info);

        //se for de alteração pegue o código do animal que esta sendo alterado.
        if(tipo == TipoJanela.ALTERACAO){
            a.setCodigo(animal.getCodigo());
        }

        return a;
    }

    protected final void desabilitarCampos() {
        campoNome.setEditable(false);
        comboSexo.setEnabled(false);
        campoDataNascimento.setEditable(false);
        comboEspecie.setEnabled(false);
        campoRaca.setEditable(false);
        areaInformacoes.setEditable(false);
    }

    @Override
    protected void cadastrar() {
        Animal a = gerarAnimal();
        janelaCliente.adicionarAnimal(a);
    }

    @Override
    protected void alterar() {
        Animal a = gerarAnimal();
        janelaCliente.alterarAnimal(a);
    }
}
